package com.goods.business.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.goods.business.mapper.ConsumerMapper;
import com.goods.business.mapper.ListMapper;
import com.goods.business.mapper.OutStockInfoMapper;
import com.goods.business.mapper.OutStockMapper;
import com.goods.business.service.OutStockService;
import com.goods.common.model.business.*;
import com.goods.common.vo.business.*;
import com.goods.common.vo.system.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OutStockServiceImpl implements OutStockService {
    @Autowired
    private OutStockMapper outStockMapper;
    @Autowired
    private ConsumerMapper consumerMapper;
    @Autowired
    private OutStockInfoMapper outStockInfoMapper;
    @Autowired
    private ListMapper listMapper;

    // 物资出库展示
    @Override
    public PageVO<OutStockVO> findOutStockList(FindOutStockQueryVo findOutStockQueryVo) {
        // 从数据库中查询所有符合条件的出库记录
        List<OutStock> outStockList = outStockMapper.findOutStockList(findOutStockQueryVo);
        // 根据消费者id查询消费人的信息
        List<OutStockVO> outStockVOList = outStockList.stream().map(outStock -> {
            OutStockVO outStockVO = new OutStockVO();
            BeanUtils.copyProperties(outStock,outStockVO);
            Consumer consumer = new Consumer();
            consumer.setId(outStock.getConsumerId());
            consumer = consumerMapper.selectOne(consumer);
            if(consumer!=null){
                // 联系方式
                outStockVO.setPhone(consumer.getPhone());
                // 发放地点
                outStockVO.setName(consumer.getName());
            }
            return outStockVO;
        }).collect(Collectors.toList());

        // 分页
        PageHelper.startPage(findOutStockQueryVo.getPageNum(),findOutStockQueryVo.getPageSize());
        PageInfo<OutStockVO> pageInfo = new PageInfo<>(outStockVOList);
        PageVO<OutStockVO> vo = new PageVO<>(pageInfo.getTotal(), outStockVOList);
        return vo;
    }

    // 物资出库明细展示
    @Override
    public OutStockDetailVO detailOutStockList(Long id, Integer pageNum, String username) {
        OutStockDetailVO outStockDetailVO = new OutStockDetailVO();
        // 查询父订单
        OutStock outStock = new OutStock();
        outStock.setId(id);
        outStock = outStockMapper.selectOne(outStock);
        // 返回-父订单状态
        outStockDetailVO.setStatus(outStock.getStatus());
        // 获取消费者
        Long consumerId = outStock.getConsumerId();
        Consumer consumer = new Consumer();
        consumer.setId(consumerId);
        consumer = consumerMapper.selectOne(consumer);
        // 返回-消费者信息
        ConsumerVO consumerVO = new ConsumerVO();
        BeanUtils.copyProperties(consumer,consumerVO);
        outStockDetailVO.setConsumerVO(consumerVO);
        // 根据出库单查询子订单
        String outNum = outStock.getOutNum();
        OutStockInfo outStockInfo = new OutStockInfo();
        outStockInfo.setOutNum(outNum); // 出库订单
        List<OutStockInfo> outStockInfoList = outStockInfoMapper.select(outStockInfo);
        // 对子订单数据的封装
        List<OutStockItemVO> outStockItemVOS =  outStockInfoList.stream().map(o -> {
            OutStockItemVO outStockItemVO = new OutStockItemVO();
            // 商品数量
            outStockItemVO.setCount(o.getProductNumber());
            // id
            outStockItemVO.setId(o.getId());
            // 根据商品编号查询商品信息
            String pNum = o.getPNum(); // 商品编号
            Product product = new Product();
            product.setPNum(pNum);
            product = listMapper.selectOne(product);
            // pNum
            outStockItemVO.setPNum(pNum);
            // name
            outStockItemVO.setName(product.getName());
            // model
            outStockItemVO.setModel(product.getModel());
            // unit
            outStockItemVO.setModel(product.getUnit());
            // imageUrl
            outStockItemVO.setImageUrl(product.getImageUrl());
            // unit
            outStockItemVO.setUnit(product.getUnit());
            return outStockItemVO;
        }).collect(Collectors.toList());
        // 返回-每一个子出库
        outStockDetailVO.setItemVOS(outStockItemVOS);
        // 开启分页
        PageHelper.startPage(pageNum,3);
        PageInfo<OutStockItemVO> outStockItemVOPageInfo = new PageInfo<>(outStockItemVOS);
        // 返回-总条数
        outStockDetailVO.setTotal(outStockItemVOPageInfo.getTotal());

        return outStockDetailVO;
    }

    // 从回收站还原
    @Override
    public void changeOutStockListStatus(Long id, int status) {
        OutStock outStock = new OutStock();
        outStock.setId(id);
        outStock = outStockMapper.selectOne(outStock);
        outStock.setStatus(status);
        outStockMapper.updateByPrimaryKey(outStock);
    }

    // 删除出库
    @Override
    @Transactional
    public void deleteOutStockList(Long id) {
        // 根据id查询
        OutStock outStock = new OutStock();
        outStock.setId(id);
        outStock = outStockMapper.selectOne(outStock);
        // 获取出库单号
        String outNum = outStock.getOutNum();
        // 查询子订单
        OutStockInfo outStockInfo = new OutStockInfo();
        outStockInfo.setOutNum(outNum);
        List<OutStockInfo> outStockInfoList = outStockInfoMapper.select(outStockInfo);
        // 删除子订单
        if(outStockInfoList!=null){
            for (OutStockInfo stockInfo : outStockInfoList) {
                outStockInfoMapper.delete(stockInfo);
            }
        }
        // 删除主订单
        outStockMapper.delete(outStock);
    }

    // 添加入库
    @Override
    public void addOutStock(OutStockVO outStockVO, String username) {
        // 1、消费者
        Long consumerId = outStockVO.getConsumerId();
        if(consumerId==null){ // 需要新增来源
            consumerId = insertConsumer(outStockVO);
        }

        // 2、生成随机订单号
        String outNum = UUID.randomUUID().toString().replaceAll("-", "");

        // 3.入库详情 [{productId: 46, productNumber: 2}, {productId: 40, productNumber: 1},...]
        List<Object> products = outStockVO.getProducts();
        Integer countNum = 0;
        for (Object o : products) {
            Map map = JSONObject.parseObject(JSONObject.toJSONString(o),Map.class);
            Long productId = Long.valueOf(map.get("productId").toString()); // 商品id
            Integer productNum = Integer.valueOf(map.get("productNumber").toString()); // 商品数量
            countNum+=productNum; // 累加数量
            // 根据id查出商品详情
            Product product = new Product();
            product.setId(productId);
            product = listMapper.selectOne(product);
            // 入库详情表
            OutStockInfo outStockInfo = new OutStockInfo();
            outStockInfo.setOutNum(outNum); // 出库号
            outStockInfo.setPNum(product.getPNum()); // 商品号
            outStockInfo.setProductNumber(productNum); // 商品数量
            outStockInfo.setCreateTime(new Date());
            outStockInfo.setModifiedTime(new Date());
            // 出库
            outStockInfoMapper.insert(outStockInfo);
        }

        // 4.出库
        OutStock outStock = new OutStock();
        outStock.setOutNum(outNum); // 商品号
        outStock.setConsumerId(consumerId); // 来源联系人的id
        outStock.setStatus(2); // 状态 默认新增加的为待审核
        outStock.setOperator(username); // 操作者
        outStock.setRemark(outStockVO.getRemark()); // 备注
        outStock.setType(outStockVO.getType()); // 类型
        outStock.setCreateTime(new Date());
        outStock.setPriority(outStockVO.getPriority());
        outStock.setProductNumber(countNum); // 总数量
        outStockMapper.insert(outStock);
    }

    private Long insertConsumer(OutStockVO outStockVO) {
        Consumer consumer = new Consumer();
        consumer.setContact(outStockVO.getContact());
        consumer.setSort(outStockVO.getSort());
        consumer.setPhone(outStockVO.getPhone());
        consumer.setAddress(outStockVO.getAddress());
        consumer.setName(outStockVO.getName());
        consumer.setCreateTime(new Date());
        consumer.setModifiedTime(new Date());
        consumerMapper.insert(consumer);
        return consumer.getId();
    }
}
